package repository

import (
	"context"
	"server/internal/app/model"
	"server/internal/core/store"

	"gorm.io/gorm"
)

type SysAdminRoleRepository struct {
	db *gorm.DB
}

func NewSysAdminRoleRepository() *SysAdminRoleRepository {
	return &SysAdminRoleRepository{db: store.DB}
}

func (r *SysAdminRoleRepository) All(ctx context.Context) ([]model.SysAdminRole, error) {
	var adminRoles []model.SysAdminRole
	err := r.db.WithContext(ctx).Find(&adminRoles).Error
	return adminRoles, err
}

// 分配角色
func (r *SysAdminRoleRepository) AssignRole(ctx context.Context, adminID uint, roleID ...uint) error {
	// 先删除已有的角色
	err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if err := tx.Delete(&model.SysAdminRole{}, "admin_id = ?", adminID).Error; err != nil {
			return err
		}
		//批量插入
		adminRoles := make([]model.SysAdminRole, len(roleID))
		for i, roleID := range roleID {
			adminRoles[i] = model.SysAdminRole{
				AdminID: adminID,
				RoleID:  roleID,
			}
		}
		if err := tx.CreateInBatches(&adminRoles, 100).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}
